/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.engine.entity.propertyinfobuilder.cef;

import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.bef.bizentity.common.BefDtBeanUtil;
import com.inspur.edp.bef.engine.entity.exception.BefEngineExceptionBase;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.element.ForeignKeyConstraintType;
import com.inspur.edp.cef.designtime.api.element.GspAssociation;
import com.inspur.edp.cef.designtime.api.element.GspAssociationKey;
import com.inspur.edp.cef.spi.entity.AssociationEnableState;
import com.inspur.edp.cef.spi.entity.AssociationInfo;
import com.inspur.edp.cef.spi.entity.info.propertyinfo.AssocationPropertyInfo;
import com.inspur.edp.cef.spi.entity.info.propertyinfo.BasePropertyInfo;
import com.inspur.edp.commonmodel.engine.api.common.CMEngineUtil;
import com.inspur.edp.das.commonmodel.IGspCommonObject;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationRtService;
import org.springframework.util.StringUtils;

public class AssoPropInfoBuilder extends BasePropertyInfoBuilder {

  public AssoPropInfoBuilder(IGspCommonField field,
      CefPropInfoGenerator propInfoGenerator) {
    super(field, propInfoGenerator);
  }


  private GspBusinessEntity getRefEntity(String id) {
    return CMEngineUtil.getMetadataContent(id);
  }

  protected GspAssociation getAssociation()
  {
    return field.getChildAssociations().get(0);
  }

  @Override
  public BasePropertyInfo getBasePropertyInfo(IGspCommonField field) {
    GspAssociation asso = getAssociation();
    if(asso == null || StringUtils.isEmpty(asso.getRefModelID())) {
      throw new BefEngineExceptionBase(String
          .format("节点[%s]上字段[%s]的关联信息不存在, 请修改", field.getBelongObject().getCode(),
              field.getLabelID()));
    }
    GspBusinessEntity refEntity = getRefEntity(asso.getRefModelID());
    if(refEntity == null) {
      throw new BefEngineExceptionBase(String
          .format("节点[%s]上的字段[%s]关联的ID,名称分别为[%s],[%s]的业务实体元数据获取不到(调用接口为com.inspur.edp.lcm.metadata.api.service.MetadataRTService.getMetadata(MetadataCustomizationFilter)),"
                  + "请联系被关联业务实体的开发人员检查是否正确部署, 通常正确部署后gspmdrtcontent表中应存在此元数据相关信息",
              field.getBelongObject().getCode(),
              field.getLabelID(), asso.getRefModelID(), asso.getRefModelName()));
    }
    return getAssoPropertyInfo(field,getAssociation(), refEntity, propInfoGenerator);
  }

  public static AssocationPropertyInfo getAssoPropertyInfo(IGspCommonField field,GspAssociation association,GspBusinessEntity refEntity,CefPropInfoGenerator propInfoGenerator) {
    AssociationInfo associationInfo = new AssociationInfo();
    associationInfo.setConfig(refEntity.getGeneratedConfigID());
    associationInfo
        .setNodeCode(getObjectByAssociation(association, refEntity).getCode());
    associationInfo.setMainCode(refEntity.getMainObject().getCode());
    setEnableState(associationInfo,association);
    setAssoKeys(associationInfo,field,association,refEntity);
    setRefProperties(associationInfo,association,propInfoGenerator,
        getObjectByAssociation(association, refEntity),refEntity);
    associationInfo.setKeepAssoPropertyForExpression(association.isKeepAssoPropertyForExpression());

    EngineAssoPropertyInfo assocationPropertyInfo = new EngineAssoPropertyInfo(associationInfo,association);
    return assocationPropertyInfo;
  }

  private static IGspCommonObject getObjectByAssociation(GspAssociation association,
      GspBusinessEntity refEntity) {
    IGspCommonObject result = null;
    if(!StringUtils.isEmpty(association.getRefObjectID())) {
      result = refEntity.findObjectById(association.getRefObjectID());
    }
    if(result == null && !StringUtils.isEmpty(association.getRefObjectCode())) {
      result = refEntity.findObjectByCode(association.getRefObjectCode());
    }
    if(result==null){
      throw new BefEngineExceptionBase(String
          .format("关联模型[%1$s]上未获取到ID为[%2$s]，编号为[%3$s]的节点对象,请检查确认元数据是否修改或是否正确部署", refEntity.getCode(),
              association.getRefModelID(), association.getRefModelCode()));
    }
    return result;
  }

  private static  void setRefProperties(AssociationInfo associationInfo, GspAssociation association, CefPropInfoGenerator propInfoGenerator, IGspCommonObject objectById, GspBusinessEntity refEntity) {
    for(IGspCommonField refField:association.getRefElementCollection())
    {
      IGspCommonField refedField = objectById.findElement(refField.getRefElementId());
      if(refedField==null)
        throw new BefEngineExceptionBase("检查字段'"+association.getBelongElement().getName()+"'的关联带出字段'"+refField.getName()+"'时出错，在被关联的业务实体'"+refEntity.getName()+"'中找不到该字段。");
      associationInfo.addRefProp(refField.getLabelID(),propInfoGenerator.getAssociationRefPropertyInfo(refField,refedField));
    }
  }

  private static void setAssoKeys(AssociationInfo associationInfo,IGspCommonField  field,GspAssociation association,GspBusinessEntity refEntity) {
    setPrivateSourceColumn(associationInfo,association,refEntity);
    setPrivateTargetColumn(associationInfo,field);
  }

  private static void setPrivateTargetColumn(AssociationInfo associationInfo,IGspCommonField  field) {
    if(field.getIsRefElement()) {
      GspBusinessEntity entity = CMEngineUtil.getMetadataContent(field.getParentAssociation().getRefModelID());
      associationInfo.setPrivateTargetColumn(entity.findElementById(field.getRefElementId()).getLabelID());

    }
    else
    associationInfo.setPrivateTargetColumn(field.getLabelID());
  }

  private  static void setPrivateSourceColumn(AssociationInfo associationInfo,GspAssociation association,GspBusinessEntity refEntity) {
    String sourceElementId = "";
    for(GspAssociationKey key: association.getKeyCollection()){
      sourceElementId = key.getSourceElement();
    }
    IGspCommonObject commonObject= getObjectByAssociation(association, refEntity);
    if(commonObject==null){
      throw new BefEngineExceptionBase(String
          .format("关联模型[%1$s]上未获取到ID为[%2$s]，编号为[%3$s]的节点对象,请检查确认元数据是否修改或是否正确部署", refEntity.getCode(),
              association.getRefModelID(), association.getRefModelCode()));
    }
    IGspCommonField sourceElement =commonObject.findElement(sourceElementId);

    if(sourceElement==null){
      throw new BefEngineExceptionBase(String
          .format("节点对象[%1$s]上未获取到ID为[%2$s]的字段,请检查确认元数据是否修改或是否正确部署", commonObject.getCode(),
              sourceElementId));
    }
    associationInfo.setPrivateSourceColumn(sourceElement.getLabelID());
  }

  private static void setEnableState(AssociationInfo associationInfo,GspAssociation association) {
    associationInfo.setEnableState(association.getForeignKeyConstraintType() == ForeignKeyConstraintType.Forbid
        ? AssociationEnableState.Disabled
        : AssociationEnableState.Enabled);
  }
}
